<!--
  XAIChat.vue - X.AI API聊天组件
  功能：
  1. 提供与X.AI API的实时对话界面
  2. 支持发送和接收消息
  3. 自动显示对话主题
  4. 支持消息历史记录和滚动
  5. 提供清除对话功能
-->
<template>
  <div class="chat-container">
    <!-- 聊天主题 -->
    <div v-if="currentTopic" class="chat-topic">
      <el-icon><ChatDotRound /></el-icon>
      <span>当前话题: {{ currentTopic }}</span>
    </div>

    <!-- 消息列表 -->
    <div ref="messagesContainer" class="message-container">
      <template v-if="messages.length === 0">
        <div class="welcome-message">
          <el-icon class="service-icon"><Service /></el-icon>
          <h2>欢迎使用 X.AI 助手  Grok-beta ·免开VPN</h2>
          <p>我可以帮助你回答问题、编写代码、解决问题等。</p>
          <p>请在下方输入你的问题，按Enter发送。</p>
        </div>
      </template>
      <template v-else>
        <div v-for="(message, index) in messages" 
             :key="index" 
             :class="['message', message.role === 'user' ? 'user-message' : message.role === 'assistant' ? 'ai-message' : 'error-message']">
          <div class="message-avatar">
            <el-icon :size="36">
              <component :is="message.role === 'user' ? User : message.role === 'assistant' ? Service : null" />
            </el-icon>
          </div>
          <div class="message-content">
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ new Date().toLocaleTimeString() }}</div>
          </div>
        </div>
      </template>
    </div>

    <!-- 输入区域 -->
    <div class="input-container">
      <el-input
        v-model="userInput"
        type="textarea"
        :rows="3"
        :placeholder="loading ? '正在思考中...' : '输入消息，按Enter发送，Shift+Enter换行'"
        @keydown.enter.exact.prevent="handleSend"
        @keydown.shift.enter.exact="newLine"
        :disabled="loading"
        resize="none"
      >
        <template #prefix>
          <el-icon><ChatLineRound /></el-icon>
        </template>
      </el-input>
      <el-button 
        type="primary" 
        @click="handleSend"
        :loading="loading"
        :disabled="!userInput.trim() || loading"
      >
        <el-icon v-if="!loading"><Position /></el-icon>
        <el-icon v-else><Loading /></el-icon>
        <span>{{ loading ? '思考中...' : '发送' }}</span>
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { defineOptions } from 'vue'

defineOptions({
  name: 'XAIChat'
})

import { ref, nextTick, onMounted, computed } from 'vue';
import { ChatDotRound, ChatLineRound, Service, User, Position, Loading } from '@element-plus/icons-vue';
import { sendMessage as sendXAIMessage, createUserMessage, createAssistantMessage } from '../services/xaiService';
import { ElMessage } from 'element-plus';

// 初始化状态
const messages = ref([]);
const userInput = ref('');
const loading = ref(false);
const messagesContainer = ref(null);


// 在 ChatGPT.vue 中添加
import { onActivated, onDeactivated } from 'vue';

// 组件被激活时触发
onActivated(() => {
  console.log('XAIChat Component activated');
  nextTick(() => {
    if (messagesContainer.value) {  // 注意这里是 messagesContainer
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
});
// 组件被停用时触发
onDeactivated(() => {
  console.log('Component deactivated');
  // 可以在这里处理一些停用时的逻辑
});




// 计算当前对话主题：使用第一条用户消息作为主题
const currentTopic = computed(() => {
  const userMessages = messages.value.filter(msg => msg.role === 'user');
  if (userMessages.length > 0) {
    const firstMessage = userMessages[0].content;
    return firstMessage.length > 10 ? firstMessage.slice(0, 10) + '...' : firstMessage;
  }
  return '';
});

// 添加延迟函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// 滚动到消息底部
const scrollToBottom = async () => {
  await nextTick();
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 处理换行：Shift + Enter时在光标位置插入换行符
const newLine = (e) => {
  const cursorPosition = e.target.selectionStart;
  userInput.value = userInput.value.slice(0, cursorPosition) + '\n' + userInput.value.slice(cursorPosition);
};

// 处理发送消息
const handleSend = async () => {
  if (!userInput.value.trim() || loading.value) return;
  
  // console.log('\n=== Message Send Start ===');
  // console.log('User Input:', userInput.value);
  
  // 添加用户消息到对话列表
  const userMessage = createUserMessage(userInput.value);
  console.log('Created User Message:', userMessage);
  
  messages.value.push(userMessage);
  // console.log('Current Messages:', messages.value);
  
  loading.value = true;
  const currentInput = userInput.value;
  userInput.value = '';
  await scrollToBottom();
  
  try {
    // 添加1秒延迟
    await delay(100);

    // 发送消息到API并处理响应
    // console.log('Sending message to API...');
    const response = await sendXAIMessage([userMessage]);
    // console.log('API Response:', JSON.stringify(response, null, 2));

    // 处理API响应
    if (response.choices && response.choices.length > 0) {
      const assistantMessage = response.choices[0].message.content;
      messages.value.push({
        role: 'assistant',
        content: assistantMessage
      });
    }else {
      console.error('No response from API or empty choices:', response);
     
       ElMessage({
       code: response.code||'未知错误码',
        message: response.error||'未知错误',
      });
    }

    // 显示错误消息
    if (response.error) {
      console.error('API Error:', response.error);
      // throw {  //会导致catch抛出错误
      //   error: response.error,
      //   response: response
      // }
    }
    
  } catch (error) {
    console.error('Message Send Error:', error);
    console.error('Error Response:', error.response);
    console.log('Messages after error:', messages);

    // 显示错误消息
    messages.value.push({
      role: 'error',
      content: error.isApiError 
        ? `❌ ${error.message}`
        : '❌ 发送消息时出现错误，请稍后重试'
    });
  } finally {
    loading.value = false;
    await scrollToBottom();
    console.log('=== Message Send End ===\n');
  }
};

// 清除对话历史
const handleClearChat = () => {
  messages.value = [];
};

// 组件挂载时初始化
onMounted(() => {
  scrollToBottom();
});
</script>

<style lang="scss" scoped>

.home-view {
  height: 100vh;
  padding-top: 1rem;
}


/* 聊天容器样式 */
.chat-container {
  // max-width: 800px;
  margin: 0 auto;
  height: 95vh;
  max-height: 95vh;
  max-height: calc(100% - 100px);
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-top: 10px;

 
}

/* 聊天主题样式 */
.chat-topic {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0.5rem 1rem;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 0.9rem;
  color: #606266;
}

/* 消息容器样式 */
.message-container {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  border: 1px solid #f1f2f5;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: inset 0 0 2px 0 rgba(0, 0, 0, 0.1);
}

/* 欢迎消息样式 */
.welcome-message {
  text-align: center;
  padding: 2rem;
  color: #606266;
}

.welcome-message h2 {
  margin: 1rem 0;
  color: #303133;
}

.welcome-message p {
  margin: 0.5rem 0;
  color: #909399;
}

/* 消息样式 */
.message {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
  max-width: 93%;
}

.user-message {
  margin-left: auto;
  flex-direction: row-reverse;
}

.ai-message {
  margin-right: auto;
}

.error-message {
  margin: 0 auto;
  text-align: center;
  color: #f56c6c;
}

.message-avatar {
  flex-shrink: 0;
  
  
}

#app > .message-avatar > .el-icon {
  font-size: 24px;
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 0px 2px;
  font-size: 12px;

}

.message-text {
  padding: 0.8rem 1rem;
  border-radius: 8px;
  line-height: 1.5;
  white-space: pre-wrap;
  font-size: 12px;
}

.user-message .message-text {
  background-color: #409eff;
  color: white;
}

.ai-message .message-text {
  background-color: #f5f7fa;
  color: #303133;
}

.error-message .message-text {
  background-color: #fef0f0;
  color: #f56c6c;
}

.message-time {
  font-size: 0.8rem;
  color: #909399;
  text-align: right;
}

/* 输入区域样式 */
.input-container {
  display: flex;
  gap: 1rem;
  align-items: flex-start;
  padding: 1rem;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.input-container :deep(.el-input__wrapper) {
  background-color: #fff;
}

.input-container :deep(.el-textarea__inner) {
  min-height: 60px !important;
  resize: none;
}

.input-container .el-button {
  height: auto;
  max-height: 82px;
  min-height: 40px;
  padding: 0 2rem;
}

/* 滚动条样式 */
.message-container::-webkit-scrollbar {
  width: 6px;
}

.message-container::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.message-container::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

/* 移动端和竖屏适配 */
@media screen and (max-width: 768px), (orientation: portrait) {
  .chat-container {
    padding: 0;
    height: 100vh;
    margin: 0;
    border-radius: 0;
    box-shadow: none;
  }

  .chat-topic {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(8px);
    padding: 10px 15px;
    margin: 0;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }

  .message-container {
    margin-top: 50px;
    margin-bottom: 70px;
    padding: 10px;
  }

  .message {
    max-width: 85%;
  }

  .message-text {
    font-size: 14px;
  }

  .input-container {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(8px);
    box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.1);
    padding: 10px;
    margin: 0;
    border-radius: 0;
  }

  .input-container :deep(.el-textarea__inner) {
    min-height: 40px !important;
    padding-right: 90px;
  }

  .input-container .el-button {
    position: absolute;
    right: 10px;
    bottom: 15px;
    min-height: 36px;
    padding: 0 15px;
    font-size: 14px;
  }
}
</style>
